package com.victor.utils;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;

import com.alibaba.fastjson.JSON;

public class SMSUtils {

	private static Logger log = LoggerFactory.getLogger(SMSUtils.class);

	private static String KEY = "fa604ba76d4dad3c";

	public static void main(String[] args) {
		// 创建模板
//		templateCreateTest();

		// 发送测试
		smsSendTest();
	}

	/**
	 * 创建模板
	 */
	public static void templateCreateTest() {
		try {
			TreeMap<String, Object> map = new TreeMap<String, Object>();
			map.put("cpid", 2907);
			map.put("name", "旅游鸭模板");
			map.put("sign", "旅游鸭");
			map.put("content", "您的验证码是:${code},谢谢您的使用！");

			map.put("timestamp", new Date().getTime());

			String _sign = createSign(map);
			System.out.println("sign:" + _sign);
			String sign = getKeyedDigestGBK(_sign, KEY);
			System.out.println(sign);

			map.put("verify", sign);

			String resource = "http://api.hstang.net/service/template/create";

//	            HttpClient httpClient = HttpUtils.getSecuredHttpClient();
			CloseableHttpClient httpClient = HttpClientBuilder.create().build();

			String body = JSON.toJSONString(map);
			log.info(body);
			HttpPost post = new HttpPost(resource);
			StringEntity se = new StringEntity(body, "UTF-8");
			se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
			post.addHeader("Content-Type", "application/json;charset=UTF-8");
			post.addHeader("accept", "application/json");
			post.setEntity(se);
			HttpResponse httpResponse = httpClient.execute(post);
			log.info(String.valueOf(httpResponse.getStatusLine().getStatusCode()));
			log.info(IOUtils.toString(httpResponse.getEntity().getContent()));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
	}

	/**
	 * 发送测试
	 */
	public static void smsSendTest() {
		try {
			TreeMap<String, Object> map = new TreeMap<String, Object>();
			map.put("cpid", 2907);
			map.put("templateId", 11190);
			map.put("mobile", "18704074221");
			map.put("parameter", "{\"code\":\"123456\"}");
			map.put("timestamp", new Date().getTime());

			String _sign = createSign(map);
			System.out.println("sign:" + _sign);
			String sign = getKeyedDigestGBK(_sign, KEY);
			System.out.println(sign);
			map.put("verify", sign);

			String resource = "http://api.hstang.net/service/sms/send";

//            HttpClient httpClient = HttpUtils.getSecuredHttpClient();
			CloseableHttpClient httpClient = HttpClientBuilder.create().build();

			String body = JSON.toJSONString(map);
			log.info(body);
			HttpPost post = new HttpPost(resource);
			StringEntity se = new StringEntity(body, "UTF-8");
			se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
			post.addHeader("Content-Type", "application/json;charset=UTF-8");
			post.addHeader("accept", "application/json");
			post.setEntity(se);
			HttpResponse httpResponse = httpClient.execute(post);
			log.info(String.valueOf(httpResponse.getStatusLine().getStatusCode()));
			log.info(IOUtils.toString(httpResponse.getEntity().getContent()));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
	}

	public static String createSign(TreeMap<String, Object> tm) {
		StringBuffer buf = new StringBuffer();
		for (Map.Entry<String, Object> en : tm.entrySet()) {
			String name = en.getKey();
			String value = en.getValue().toString();
			if (value != null && value.length() > 0 && !"null".equals(value)) {
				buf.append(name).append('=').append(value).append('&');
			}
		}
		String _buf = buf.toString();
		return _buf.substring(0, _buf.length() - 1);
	}

	public static String getKeyedDigestGBK(String strSrc, String key) {
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(strSrc.getBytes("GBK"));
			String result = "";
			byte[] temp;
			temp = md5.digest(key.getBytes("UTF8"));
			for (int i = 0; i < temp.length; i++) {
				result += Integer.toHexString((0x000000ff & temp[i]) | 0xffffff00).substring(6);
			}
			return result.toUpperCase();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 文件转String
	 *
	 * @param fileName
	 * @return
	 * @throws Exception
	 */
	public static String readFileAsString(String fileName) throws Exception {
		FileInputStream fis = new FileInputStream(fileName);
		BufferedInputStream in = new BufferedInputStream(fis);
		byte buffer[] = new byte[256];
		StringBuffer picStr = new StringBuffer();
		BASE64Encoder base64 = new BASE64Encoder();
		while (in.read(buffer) >= 0) {
			picStr.append(base64.encode(buffer));// 进行64位编码
		}
		fis.close();
		fis = null;
		in.close();
		in = null;
		buffer = null;
		return picStr.toString();
	}

}
